package com.ruoyi.miniapp.service.impl;

import com.ruoyi.miniapp.api.domain.MiniappRole;
import com.ruoyi.miniapp.api.domain.MiniappUser;
import com.ruoyi.miniapp.service.IMiniappMenuService;
import com.ruoyi.miniapp.service.IMiniappPermissionService;
import com.ruoyi.miniapp.service.IMiniappRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MiniappPermissionServiceImpl implements IMiniappPermissionService {
    @Autowired
    private IMiniappRoleService     iMiniappRoleService;

    @Autowired
    private IMiniappMenuService iMiniappMenuService;
    @Override
    public Set<String> getRolePermission(MiniappUser miniappUser) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (miniappUser.isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(iMiniappRoleService.selectRolePermissionByUserId(miniappUser.getUserId()));
        }
        return roles;
    }

    @Override
    public Set<String> getMenuPermission(MiniappUser miniappUser) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (miniappUser.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<MiniappRole> roles = miniappUser.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (MiniappRole miniappRole : roles)
                {
                    Set<String> rolePerms = iMiniappMenuService.selectMenuPermsByRoleId(miniappRole.getRoleId());
                    miniappRole.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            }
            else
            {
                perms.addAll(iMiniappMenuService.selectMenuPermsByUserId(miniappUser.getUserId()));
            }
        }
        return perms;
    }
}
